package com.dyx.api.files.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dyx.api.utils.RequestMessage;
import com.dyx.gateway.common.context.ContextHolder;
import com.dyx.spring.boot.api.registry.RestDiscovery2Zookeeper;
import org.json.JSONException;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.annotations.ApiIgnore;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by 谭磊 on 2017/7/27 0027.
 * 基础公用controller
 */
@ApiIgnore
@Component
public class BaseController {


    @Autowired
    RestTemplate restTemplate;
    @Resource(name = "restDiscovery2Zookeeper")
    private RestDiscovery2Zookeeper restDiscovery2Zookeeper;


    /**
     * 获取空数据的返回对象
     * @return
     */
    public String returnNullDataMessage(){
        RequestMessage message = new RequestMessage();
        message.setErrorNo(0);
        message.setErrorMsg("访问成功!");
        message.setResData(new Object());
        return JSON.toJSONString(message);
    }

    /**
     * 获取有数据的返回对象
     * @param object:返回的数据
     * @return
     */
    public String returnSuccessMessage(Object object){
        RequestMessage message = new RequestMessage();
        message.setErrorNo(0);
        message.setErrorMsg("访问成功!");
        message.setResData(object);
        return JSON.toJSONString(message);
    }

    /**
     * 获取有数据的返回对象
     * @param msg:返回的错误信息
     * @return
     */
    public String returnErrorMessage(String msg){
        RequestMessage message = new RequestMessage();
        message.setErrorNo(1);
        message.setErrorMsg(msg);
        message.setResData(new Object());
        return JSON.toJSONString(message);
    }

    /**
     * 获取有数据的返回对象
     * @param msg:返回的错误信息
     * @return
     */
    public JSONObject returnSelectErrorMessage(String msg){
        RequestMessage message = new RequestMessage();
        message.setErrorNo(1);
        message.setErrorMsg(msg);
        message.setResData(new Object());
        return JSONObject.parseObject(JSON.toJSONString(message));
    }

    /**
     * 访问其他模块的封装方法
     * @param moduleName:模块名
     * @param requestPath:请求路径
     * @param param
     * @return
     */
    public JSONObject selectOtherModule(String moduleName, String requestPath, JSONObject param){
        JSONObject resultData = new JSONObject();
        String path = "";
        try {
            path = this.restDiscovery2Zookeeper.remotePath4BackendService(moduleName, requestPath, 0);
            resultData=this.restTemplate.postForObject(path, param, JSONObject.class);
            return resultData;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(path);
            return returnSelectErrorMessage("服务器繁忙,请稍后重试!");
        }
    }

    /**
     * 访问其他模块的封装方法
     * @param moduleName:模块名
     * @param requestPath:请求路径
     * @param map
     * @return
     */
    public JSONObject FileToOtherModule(String moduleName, String requestPath, MultiValueMap<String, Object> map){
        JSONObject resultData = new JSONObject();
        String path = "";
        try {
            path = this.restDiscovery2Zookeeper.remotePath4BackendService(moduleName, requestPath, 0);
            String str = this.restTemplate.postForObject(path, map, String.class);
            return new JSONObject();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(path);
            return returnSelectErrorMessage("服务器繁忙,请稍后重试!");
        }
    }


    /**
     * 获取session里的用户信息
     * @return
     */
    public JSONObject getSessionUser(){
        JSONObject user = new JSONObject();
        Map<String,Object> map= ContextHolder.currentAccount();
        for(String users:map.keySet()){
            user.put(users,map.get(users));
        }
        return user.getJSONObject("resData").getJSONObject("data");
    }

    public String getSessionTenName(){
        return getSessionUser().getString("userTel");
    }

    /**
     * 获取session用户id
     * @return
     */
    public String getSessionUserId(){
        return ContextHolder.currentAccountId();
    }

    /**
     * 获取session用户租户id
     * @return
     */
    public String getSessionUserLesseeId(){
        JSONObject user = getSessionUser();
        return user.getString("tenId");
    }

    public String getAllTime(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
        return date;
    }

    /**
     * 得到本机的外网ip，出现异常时返回空串""
     * @return
     */
    public static String getPublicIP(ServletRequest request) {
        return request.getRemoteAddr();
    }

    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = null;
        try {
            is = new URL(url).openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = JSON.parseObject(jsonText);
            return json;
        } finally {
            //关闭输入流
            is.close();
        }
    }

    public static String getAddrName(ServletRequest request) throws JSONException, IOException {
        //这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
        JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=iTrwV0ddxeFT6QUziPQh2wgGofxmWkmg&ip="+getPublicIP(request));
        /* 获取到的json对象：
         *         {"address":"CN|河北|保定|None|UNICOM|0|0",
         *        "content":{"address_detail":{"province":"河北省","city":"保定市","street":"","district":"","street_number":"","city_code":307},
         *        "address":"河北省保定市","point":{"x":"12856963.35","y":"4678360.5"}},
         *        "status":0}
        */
//　　　　　这里我们可以输出json看一下具体格式
        System.out.println(json.toString());

        JSONObject content=json.getJSONObject("content");              //获取json对象里的content对象
        JSONObject addr_detail=content.getJSONObject("address_detail");//从content对象里获取address_detail
        String city=addr_detail.get("city").toString();                //获取市名，可以根据具体需求更改，如果需要获取省份的名字，可以把“city”改成“province”...
        return city;
    }

}
